<template>
  <div class="settings-view">
    <!-- 设置导航 -->
    <div class="settings-nav">
      <el-menu
        :default-active="activeSection"
        mode="vertical"
        @select="handleSectionChange"
      >
        <el-menu-item index="profile">
          <el-icon><User /></el-icon>
          <span>个人资料</span>
        </el-menu-item>
        <el-menu-item index="account">
          <el-icon><Lock /></el-icon>
          <span>账户安全</span>
        </el-menu-item>
        <el-menu-item index="preferences">
          <el-icon><Setting /></el-icon>
          <span>偏好设置</span>
        </el-menu-item>
        <el-menu-item index="notifications">
          <el-icon><Bell /></el-icon>
          <span>通知设置</span>
        </el-menu-item>
        <el-menu-item index="privacy">
          <el-icon><View /></el-icon>
          <span>隐私设置</span>
        </el-menu-item>
        <el-menu-item index="data">
          <el-icon><Download /></el-icon>
          <span>数据管理</span>
        </el-menu-item>
        <el-menu-item index="subscription">
          <el-icon><CreditCard /></el-icon>
          <span>订阅管理</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 设置内容 -->
    <div class="settings-content">
      <!-- 个人资料 -->
      <div v-if="activeSection === 'profile'" class="settings-section">
        <div class="section-header">
          <h2>个人资料</h2>
          <p>管理您的个人信息和头像</p>
        </div>
        <el-form
          ref="profileFormRef"
          :model="profileForm"
          :rules="profileRules"
          label-width="100px"
        >
          <el-form-item label="头像">
            <div class="avatar-section">
              <el-avatar :size="80" :src="profileForm.avatar">
                {{ profileForm.nickname?.charAt(0) || "U" }}
              </el-avatar>
              <div class="avatar-actions">
                <el-upload
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="uploadAvatar"
                >
                  <el-button type="primary" size="small">更换头像</el-button>
                </el-upload>
                <el-button size="small" @click="removeAvatar">移除</el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="profileForm.nickname" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="个人简介" prop="bio">
            <el-input
              v-model="profileForm.bio"
              type="textarea"
              :rows="3"
              placeholder="介绍一下自己吧"
            />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profileForm.gender">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
              <el-radio label="other">其他</el-radio>
              <el-radio label="">不透露</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="profileForm.birthday"
              type="date"
              placeholder="选择生日"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="所在地" prop="location">
            <el-input
              v-model="profileForm.location"
              placeholder="请输入所在地"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveProfile" :loading="saving">
              保存更改
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 账户安全 -->
      <div v-if="activeSection === 'account'" class="settings-section">
        <div class="section-header">
          <h2>账户安全</h2>
          <p>管理您的登录信息和安全设置</p>
        </div>

        <!-- 邮箱设置 -->
        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>邮箱地址</span>
              <el-tag :type="user.emailVerified ? 'success' : 'warning'">
                {{ user.emailVerified ? "已验证" : "未验证" }}
              </el-tag>
            </div>
          </template>
          <div class="security-item">
            <div class="item-info">
              <p>当前邮箱：{{ user.email }}</p>
              <p class="item-desc">用于登录和接收重要通知</p>
            </div>
            <div class="item-actions">
              <el-button v-if="!user.emailVerified" type="primary" size="small">
                验证邮箱
              </el-button>
              <el-button size="small" @click="showChangeEmail = true">
                更换邮箱
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 手机号设置 -->
        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>手机号码</span>
              <el-tag :type="user.phoneVerified ? 'success' : 'info'">
                {{
                  user.phone
                    ? user.phoneVerified
                      ? "已验证"
                      : "未验证"
                    : "未绑定"
                }}
              </el-tag>
            </div>
          </template>
          <div class="security-item">
            <div class="item-info">
              <p>
                {{ user.phone ? `当前手机：${user.phone}` : "未绑定手机号" }}
              </p>
              <p class="item-desc">用于账户安全验证</p>
            </div>
            <div class="item-actions">
              <el-button size="small" @click="showChangePhone = true">
                {{ user.phone ? "更换手机" : "绑定手机" }}
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 密码设置 -->
        <el-card class="security-card">
          <template #header>
            <span>登录密码</span>
          </template>
          <div class="security-item">
            <div class="item-info">
              <p>定期更换密码有助于保护账户安全</p>
              <p class="item-desc">
                上次修改：{{ formatDate(user.passwordUpdatedAt) }}
              </p>
            </div>
            <div class="item-actions">
              <el-button size="small" @click="showChangePassword = true">
                修改密码
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 两步验证 -->
        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>两步验证</span>
              <el-tag :type="user.twoFactorEnabled ? 'success' : 'info'">
                {{ user.twoFactorEnabled ? "已启用" : "未启用" }}
              </el-tag>
            </div>
          </template>
          <div class="security-item">
            <div class="item-info">
              <p>为您的账户添加额外的安全保护</p>
              <p class="item-desc">登录时需要输入手机验证码</p>
            </div>
            <div class="item-actions">
              <el-switch
                v-model="user.twoFactorEnabled"
                @change="toggleTwoFactor"
              />
            </div>
          </div>
        </el-card>
      </div>

      <!-- 偏好设置 -->
      <div v-if="activeSection === 'preferences'" class="settings-section">
        <div class="section-header">
          <h2>偏好设置</h2>
          <p>个性化您的使用体验</p>
        </div>

        <el-form :model="preferences" label-width="120px">
          <!-- 主题设置 -->
          <el-form-item label="主题模式">
            <el-radio-group
              v-model="preferences.theme"
              @change="handleThemeChange"
            >
              <el-radio label="light">浅色</el-radio>
              <el-radio label="dark">深色</el-radio>
              <el-radio label="auto">跟随系统</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 语言设置 -->
          <el-form-item label="界面语言">
            <el-select
              v-model="preferences.language"
              @change="handleLanguageChange"
            >
              <el-option label="简体中文" value="zh-CN" />
              <el-option label="English" value="en-US" />
              <el-option label="日本語" value="ja-JP" />
            </el-select>
          </el-form-item>

          <!-- 聊天设置 -->
          <el-divider content-position="left">聊天设置</el-divider>
          <el-form-item label="发送方式">
            <el-radio-group v-model="preferences.sendKey">
              <el-radio label="enter">Enter 发送</el-radio>
              <el-radio label="ctrl+enter">Ctrl+Enter 发送</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="消息音效">
            <el-switch v-model="preferences.soundEnabled" />
          </el-form-item>
          <el-form-item label="打字指示器">
            <el-switch v-model="preferences.typingIndicator" />
          </el-form-item>
          <el-form-item label="自动保存">
            <el-switch v-model="preferences.autoSave" />
          </el-form-item>

          <!-- 显示设置 -->
          <el-divider content-position="left">显示设置</el-divider>
          <el-form-item label="字体大小">
            <el-slider
              v-model="preferences.fontSize"
              :min="12"
              :max="20"
              :step="1"
              show-input
              input-size="small"
            />
          </el-form-item>
          <el-form-item label="消息密度">
            <el-radio-group v-model="preferences.messageDensity">
              <el-radio label="compact">紧凑</el-radio>
              <el-radio label="normal">标准</el-radio>
              <el-radio label="comfortable">宽松</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="显示时间戳">
            <el-switch v-model="preferences.showTimestamp" />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="savePreferences"
              :loading="saving"
            >
              保存设置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 通知设置 -->
      <div v-if="activeSection === 'notifications'" class="settings-section">
        <div class="section-header">
          <h2>通知设置</h2>
          <p>管理您接收通知的方式</p>
        </div>

        <el-form :model="notifications" label-width="150px">
          <el-form-item label="桌面通知">
            <div class="notification-item">
              <el-switch v-model="notifications.desktop" />
              <span class="notification-desc">在桌面显示新消息通知</span>
            </div>
          </el-form-item>

          <el-form-item label="邮件通知">
            <div class="notification-item">
              <el-switch v-model="notifications.email" />
              <span class="notification-desc">通过邮件接收重要通知</span>
            </div>
          </el-form-item>

          <el-form-item label="短信通知">
            <div class="notification-item">
              <el-switch v-model="notifications.sms" />
              <span class="notification-desc">通过短信接收安全提醒</span>
            </div>
          </el-form-item>

          <el-divider content-position="left">通知类型</el-divider>

          <el-form-item label="新消息">
            <el-switch v-model="notifications.newMessage" />
          </el-form-item>

          <el-form-item label="系统公告">
            <el-switch v-model="notifications.systemAnnouncement" />
          </el-form-item>

          <el-form-item label="安全提醒">
            <el-switch v-model="notifications.securityAlert" />
          </el-form-item>

          <el-form-item label="营销推广">
            <el-switch v-model="notifications.marketing" />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="saveNotifications"
              :loading="saving"
            >
              保存设置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 隐私设置 -->
      <div v-if="activeSection === 'privacy'" class="settings-section">
        <div class="section-header">
          <h2>隐私设置</h2>
          <p>控制您的信息可见性</p>
        </div>

        <el-form :model="privacy" label-width="150px">
          <el-form-item label="个人资料可见性">
            <el-radio-group v-model="privacy.profileVisibility">
              <el-radio label="public">公开</el-radio>
              <el-radio label="friends">仅好友</el-radio>
              <el-radio label="private">私密</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="在线状态">
            <div class="privacy-item">
              <el-switch v-model="privacy.showOnlineStatus" />
              <span class="privacy-desc">允许其他用户看到您的在线状态</span>
            </div>
          </el-form-item>

          <el-form-item label="聊天历史">
            <div class="privacy-item">
              <el-switch v-model="privacy.saveHistory" />
              <span class="privacy-desc">保存聊天记录到云端</span>
            </div>
          </el-form-item>

          <el-form-item label="数据分析">
            <div class="privacy-item">
              <el-switch v-model="privacy.allowAnalytics" />
              <span class="privacy-desc">允许收集匿名使用数据以改进服务</span>
            </div>
          </el-form-item>

          <el-form-item label="个性化推荐">
            <div class="privacy-item">
              <el-switch v-model="privacy.personalizedRecommendation" />
              <span class="privacy-desc">基于使用习惯提供个性化内容</span>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="savePrivacy" :loading="saving">
              保存设置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据管理 -->
      <div v-if="activeSection === 'data'" class="settings-section">
        <div class="section-header">
          <h2>数据管理</h2>
          <p>导出或删除您的数据</p>
        </div>

        <!-- 数据导出 -->
        <el-card class="data-card">
          <template #header>
            <span>数据导出</span>
          </template>
          <div class="data-item">
            <div class="item-info">
              <h4>导出个人数据</h4>
              <p>下载您的聊天记录、人格设置等数据</p>
            </div>
            <div class="item-actions">
              <el-button
                type="primary"
                @click="exportData"
                :loading="exporting"
              >
                导出数据
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 数据清理 -->
        <el-card class="data-card">
          <template #header>
            <span>数据清理</span>
          </template>
          <div class="data-item">
            <div class="item-info">
              <h4>清理聊天记录</h4>
              <p>删除所有聊天记录，此操作不可恢复</p>
            </div>
            <div class="item-actions">
              <el-button type="danger" plain @click="clearChatHistory">
                清理记录
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 账户删除 -->
        <el-card class="data-card danger-card">
          <template #header>
            <span>危险操作</span>
          </template>
          <div class="data-item">
            <div class="item-info">
              <h4>删除账户</h4>
              <p>永久删除您的账户和所有相关数据，此操作不可恢复</p>
            </div>
            <div class="item-actions">
              <el-button type="danger" @click="deleteAccount">
                删除账户
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 订阅管理 -->
      <div v-if="activeSection === 'subscription'" class="settings-section">
        <div class="section-header">
          <h2>订阅管理</h2>
          <p>管理您的订阅和付费服务</p>
        </div>

        <!-- 当前订阅 -->
        <el-card class="subscription-card">
          <template #header>
            <span>当前订阅</span>
          </template>
          <div class="subscription-info">
            <div class="plan-info">
              <h3>{{ subscription.planName }}</h3>
              <p class="plan-price">¥{{ subscription.price }}/月</p>
              <p class="plan-desc">{{ subscription.description }}</p>
            </div>
            <div class="plan-status">
              <el-tag
                :type="subscription.status === 'active' ? 'success' : 'warning'"
              >
                {{ subscription.status === "active" ? "已激活" : "已过期" }}
              </el-tag>
              <p>到期时间：{{ formatDate(subscription.expiresAt) }}</p>
            </div>
          </div>
          <div class="subscription-actions">
            <el-button v-if="subscription.status === 'active'" type="primary">
              续费
            </el-button>
            <el-button v-else type="primary"> 重新订阅 </el-button>
            <el-button plain> 升级套餐 </el-button>
          </div>
        </el-card>

        <!-- 使用统计 -->
        <el-card class="usage-card">
          <template #header>
            <span>本月使用情况</span>
          </template>
          <div class="usage-stats">
            <div class="usage-item">
              <div class="usage-label">消息数量</div>
              <div class="usage-value">
                {{ usage.messageCount }} /
                {{ subscription.limits.messageLimit }}
              </div>
              <el-progress
                :percentage="
                  (usage.messageCount / subscription.limits.messageLimit) * 100
                "
                :stroke-width="6"
              />
            </div>
            <div class="usage-item">
              <div class="usage-label">存储空间</div>
              <div class="usage-value">
                {{ formatFileSize(usage.storageUsed) }} /
                {{ formatFileSize(subscription.limits.storageLimit) }}
              </div>
              <el-progress
                :percentage="
                  (usage.storageUsed / subscription.limits.storageLimit) * 100
                "
                :stroke-width="6"
              />
            </div>
          </div>
        </el-card>

        <!-- 邀请码 -->
        <el-card class="invite-card">
          <template #header>
            <span>邀请好友</span>
          </template>
          <div class="invite-info">
            <p>邀请好友注册，双方都可获得额外使用额度</p>
            <div class="invite-code">
              <el-input v-model="inviteCode" readonly>
                <template #append>
                  <el-button @click="copyInviteCode">复制</el-button>
                </template>
              </el-input>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 更换邮箱对话框 -->
    <el-dialog v-model="showChangeEmail" title="更换邮箱" width="400px">
      <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef">
        <el-form-item label="新邮箱" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入新邮箱" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="code-input">
            <el-input v-model="emailForm.code" placeholder="请输入验证码" />
            <el-button @click="sendEmailCode" :disabled="emailCodeSending">
              {{ emailCodeSending ? "发送中..." : "发送验证码" }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showChangeEmail = false">取消</el-button>
        <el-button type="primary" @click="changeEmail" :loading="saving">
          确认更换
        </el-button>
      </template>
    </el-dialog>

    <!-- 更换手机对话框 -->
    <el-dialog v-model="showChangePhone" title="更换手机" width="400px">
      <el-form :model="phoneForm" :rules="phoneRules" ref="phoneFormRef">
        <el-form-item label="新手机" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入新手机号" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="code-input">
            <el-input v-model="phoneForm.code" placeholder="请输入验证码" />
            <el-button @click="sendPhoneCode" :disabled="phoneCodeSending">
              {{ phoneCodeSending ? "发送中..." : "发送验证码" }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showChangePhone = false">取消</el-button>
        <el-button type="primary" @click="changePhone" :loading="saving">
          确认更换
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showChangePassword" title="修改密码" width="400px">
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showChangePassword = false">取消</el-button>
        <el-button type="primary" @click="changePassword" :loading="saving">
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  User,
  Lock,
  Setting,
  Bell,
  View,
  Download,
  CreditCard,
} from "@element-plus/icons-vue";
import { userApi, fileApi } from "@/api/services";
import { useAuth } from "@/composables/useAuth";
import { useTheme } from "@/composables/useTheme";
import {
  formatDate,
  formatFileSize,
  validateEmail,
  validatePhone,
} from "@/utils";

const { user, updateProfile } = useAuth();
const { setTheme } = useTheme();

// 响应式数据
const activeSection = ref("profile");
const saving = ref(false);
const exporting = ref(false);
const emailCodeSending = ref(false);
const phoneCodeSending = ref(false);

// 对话框状态
const showChangeEmail = ref(false);
const showChangePhone = ref(false);
const showChangePassword = ref(false);

// 表单引用
const profileFormRef = ref();
const emailFormRef = ref();
const phoneFormRef = ref();
const passwordFormRef = ref();

// 个人资料表单
const profileForm = reactive({
  nickname: "",
  bio: "",
  gender: "",
  birthday: "",
  location: "",
  avatar: "",
});

// 邮箱更换表单
const emailForm = reactive({
  email: "",
  code: "",
});

// 手机更换表单
const phoneForm = reactive({
  phone: "",
  code: "",
});

// 密码修改表单
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 偏好设置
const preferences = reactive({
  theme: "light",
  language: "zh-CN",
  sendKey: "enter",
  soundEnabled: true,
  typingIndicator: true,
  autoSave: true,
  fontSize: 14,
  messageDensity: "normal",
  showTimestamp: true,
});

// 通知设置
const notifications = reactive({
  desktop: true,
  email: true,
  sms: false,
  newMessage: true,
  systemAnnouncement: true,
  securityAlert: true,
  marketing: false,
});

// 隐私设置
const privacy = reactive({
  profileVisibility: "public",
  showOnlineStatus: true,
  saveHistory: true,
  allowAnalytics: true,
  personalizedRecommendation: true,
});

// 订阅信息
const subscription = reactive({
  planName: "基础版",
  price: 0,
  description: "免费使用基础功能",
  status: "active",
  expiresAt: new Date(),
  limits: {
    messageLimit: 1000,
    storageLimit: 1024 * 1024 * 100, // 100MB
  },
});

// 使用统计
const usage = reactive({
  messageCount: 0,
  storageUsed: 0,
});

// 邀请码
const inviteCode = ref("");

// 表单验证规则
const profileRules = {
  nickname: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
};

const emailRules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { validator: validateEmail, trigger: "blur" },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};

const phoneRules = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { validator: validatePhone, trigger: "blur" },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};

const passwordRules = {
  oldPassword: [{ required: true, message: "请输入当前密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 方法
const handleSectionChange = (section: string) => {
  activeSection.value = section;
};

const loadUserData = async () => {
  try {
    // 加载用户资料
    Object.assign(profileForm, {
      nickname: user.value.nickname,
      bio: user.value.bio,
      gender: user.value.gender,
      birthday: user.value.birthday,
      location: user.value.location,
      avatar: user.value.avatar,
    });

    // 加载用户偏好
    const preferencesResponse = await userApi.getUserPreferences();
    Object.assign(preferences, preferencesResponse.data);

    // 加载通知设置
    const notificationsResponse = await userApi.getNotificationSettings();
    Object.assign(notifications, notificationsResponse.data);

    // 加载隐私设置
    const privacyResponse = await userApi.getPrivacySettings();
    Object.assign(privacy, privacyResponse.data);

    // 加载订阅信息
    const subscriptionResponse = await userApi.getSubscription();
    Object.assign(subscription, subscriptionResponse.data);

    // 加载使用统计
    const usageResponse = await userApi.getUsageStats();
    Object.assign(usage, usageResponse.data);

    // 加载邀请码
    const inviteResponse = await userApi.getInviteCode();
    inviteCode.value = inviteResponse.data.code;
  } catch (error) {
    ElMessage.error("加载用户数据失败");
  }
};

const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB");
    return false;
  }
  return true;
};

const uploadAvatar = async ({ file }: { file: File }) => {
  try {
    const formData = new FormData();
    formData.append("file", file);
    const response = await uploadApi.uploadImage(formData);
    profileForm.avatar = response.data.url;
    ElMessage.success("头像上传成功");
  } catch (error) {
    ElMessage.error("头像上传失败");
  }
};

const removeAvatar = () => {
  profileForm.avatar = "";
};

const saveProfile = async () => {
  try {
    await profileFormRef.value.validate();
    saving.value = true;
    await userApi.updateProfile(profileForm);
    await updateProfile(profileForm);
    ElMessage.success("个人资料保存成功");
  } catch (error) {
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
};

const sendEmailCode = async () => {
  try {
    emailCodeSending.value = true;
    await userApi.sendEmailVerificationCode(emailForm.email);
    ElMessage.success("验证码已发送");
  } catch (error) {
    ElMessage.error("发送失败");
  } finally {
    emailCodeSending.value = false;
  }
};

const changeEmail = async () => {
  try {
    await emailFormRef.value.validate();
    saving.value = true;
    await userApi.updateEmail(emailForm);
    ElMessage.success("邮箱更换成功");
    showChangeEmail.value = false;
    loadUserData();
  } catch (error) {
    ElMessage.error("更换失败");
  } finally {
    saving.value = false;
  }
};

const sendPhoneCode = async () => {
  try {
    phoneCodeSending.value = true;
    await userApi.sendPhoneVerificationCode(phoneForm.phone);
    ElMessage.success("验证码已发送");
  } catch (error) {
    ElMessage.error("发送失败");
  } finally {
    phoneCodeSending.value = false;
  }
};

const changePhone = async () => {
  try {
    await phoneFormRef.value.validate();
    saving.value = true;
    await userApi.updatePhone(phoneForm);
    ElMessage.success("手机号更换成功");
    showChangePhone.value = false;
    loadUserData();
  } catch (error) {
    ElMessage.error("更换失败");
  } finally {
    saving.value = false;
  }
};

const changePassword = async () => {
  try {
    await passwordFormRef.value.validate();
    saving.value = true;
    await userApi.updatePassword(passwordForm);
    ElMessage.success("密码修改成功");
    showChangePassword.value = false;
    Object.assign(passwordForm, {
      oldPassword: "",
      newPassword: "",
      confirmPassword: "",
    });
  } catch (error) {
    ElMessage.error("修改失败");
  } finally {
    saving.value = false;
  }
};

const toggleTwoFactor = async (enabled: boolean) => {
  try {
    await userApi.updateTwoFactor({ enabled });
    ElMessage.success(enabled ? "两步验证已启用" : "两步验证已关闭");
  } catch (error) {
    ElMessage.error("设置失败");
    user.value.twoFactorEnabled = !enabled;
  }
};

const handleThemeChange = (theme: string) => {
  setTheme(theme);
};

const handleLanguageChange = (language: string) => {
  // 切换语言逻辑
  ElMessage.success("语言设置已保存");
};

const savePreferences = async () => {
  try {
    saving.value = true;
    await userApi.updatePreferences(preferences);
    ElMessage.success("偏好设置保存成功");
  } catch (error) {
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
};

const saveNotifications = async () => {
  try {
    saving.value = true;
    await userApi.updateNotificationSettings(notifications);
    ElMessage.success("通知设置保存成功");
  } catch (error) {
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
};

const savePrivacy = async () => {
  try {
    saving.value = true;
    await userApi.updatePrivacySettings(privacy);
    ElMessage.success("隐私设置保存成功");
  } catch (error) {
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
};

const exportData = async () => {
  try {
    exporting.value = true;
    const response = await userApi.exportUserData();
    // 下载文件
    const blob = new Blob([response.data], { type: "application/json" });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `user-data-${Date.now()}.json`;
    link.click();
    window.URL.revokeObjectURL(url);
    ElMessage.success("数据导出成功");
  } catch (error) {
    ElMessage.error("导出失败");
  } finally {
    exporting.value = false;
  }
};

const clearChatHistory = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要清理所有聊天记录吗？此操作不可恢复。",
      "确认清理",
      {
        confirmButtonText: "清理",
        cancelButtonText: "取消",
        type: "warning",
      },
    );
    await userApi.clearChatHistory();
    ElMessage.success("聊天记录已清理");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("清理失败");
    }
  }
};

const deleteAccount = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要删除账户吗？此操作将永久删除您的所有数据，且不可恢复。",
      "确认删除账户",
      {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "error",
      },
    );
    await userApi.deleteAccount();
    ElMessage.success("账户已删除");
    // 跳转到登录页
    window.location.href = "/login";
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const copyInviteCode = async () => {
  try {
    await navigator.clipboard.writeText(inviteCode.value);
    ElMessage.success("邀请码已复制到剪贴板");
  } catch (error) {
    ElMessage.error("复制失败");
  }
};

// 生命周期
onMounted(() => {
  loadUserData();
});
</script>

<style scoped>
.settings-view {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
}

.settings-nav {
  width: 200px;
  background: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color-light);
}

.settings-nav .el-menu {
  border-right: none;
}

.settings-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.settings-section {
  max-width: 800px;
}

.section-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.section-header h2 {
  margin: 0 0 8px 0;
  color: var(--el-text-color-primary);
}

.section-header p {
  margin: 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

/* 头像设置 */
.avatar-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 安全卡片 */
.security-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-info h4 {
  margin: 0 0 4px 0;
  color: var(--el-text-color-primary);
}

.item-info p {
  margin: 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.item-desc {
  color: var(--el-text-color-placeholder) !important;
  font-size: 12px !important;
}

.item-actions {
  display: flex;
  gap: 8px;
}

/* 通知设置 */
.notification-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.notification-desc {
  color: var(--el-text-color-regular);
  font-size: 14px;
}

/* 隐私设置 */
.privacy-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.privacy-desc {
  color: var(--el-text-color-regular);
  font-size: 14px;
}

/* 数据管理 */
.data-card {
  margin-bottom: 16px;
}

.danger-card {
  border-color: var(--el-color-danger-light-7);
}

.danger-card .el-card__header {
  background: var(--el-color-danger-light-9);
  color: var(--el-color-danger);
}

.data-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-item h4 {
  margin: 0 0 4px 0;
  color: var(--el-text-color-primary);
}

.data-item p {
  margin: 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

/* 订阅管理 */
.subscription-card {
  margin-bottom: 16px;
}

.subscription-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.plan-info h3 {
  margin: 0 0 8px 0;
  color: var(--el-text-color-primary);
}

.plan-price {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-color-primary);
}

.plan-desc {
  margin: 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.plan-status {
  text-align: right;
}

.plan-status p {
  margin: 8px 0 0 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.subscription-actions {
  display: flex;
  gap: 12px;
}

/* 使用统计 */
.usage-card {
  margin-bottom: 16px;
}

.usage-stats {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.usage-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.usage-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.usage-value {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

/* 邀请码 */
.invite-card {
  margin-bottom: 16px;
}

.invite-info p {
  margin: 0 0 12px 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.invite-code {
  max-width: 300px;
}

/* 验证码输入 */
.code-input {
  display: flex;
  gap: 8px;
}

.code-input .el-input {
  flex: 1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-view {
    flex-direction: column;
  }

  .settings-nav {
    width: 100%;
    height: auto;
  }

  .settings-nav .el-menu {
    display: flex;
    overflow-x: auto;
  }

  .settings-nav .el-menu-item {
    flex-shrink: 0;
  }

  .settings-content {
    padding: 16px;
  }

  .avatar-section {
    flex-direction: column;
    align-items: flex-start;
  }

  .security-item,
  .data-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .subscription-info {
    flex-direction: column;
    gap: 16px;
  }

  .plan-status {
    text-align: left;
  }

  .subscription-actions {
    flex-wrap: wrap;
  }

  .code-input {
    flex-direction: column;
  }
}
</style>
